package com.ttl.bc.ap.stkrefund.db;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;

import java.util.ArrayList;

import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;

import com.ttl.bc.ap.ap.bean.BCAPBean;
import com.ttl.bc.ap.ap.db.BCAPDAO;

import com.ttl.bc.ap.invoice.bean.BCAPInvoiceBean;
import com.ttl.bc.ap.invoice.bean.BCAPInvoiceSubBean;
import com.ttl.bc.ap.invoice.bean.ITTL_P2;

import com.ttl.bc.ap.invoice.bo.BCAPInvoiceDAO;

import com.ttl.bc.ap.stkrefund.action.BCStkRefundForm;
import com.ttl.bc.ap.stkrefund.action.InvFindForm;
import com.ttl.bc.ap.stkrefund.bean.BCInvStkRefund;
import com.ttl.bc.ap.stkrefund.bean.BCStkRefund;
import com.ttl.bc.ap.stkrefund.bean.BCStkRefundSub;

import com.ttl.bc.master.itemunit.BCItemUnitBean;
import com.ttl.bc.processstock.bean.ProcessStockBean;
import com.ttl.bc.processstock.db.ProcessStockDAO;

import com.ttl.bc.vat.inputtax.bean.BCInputTaxBean;
import com.ttl.bc.vat.inputtax.db.BCInputTaxBO;
import com.ttl.bc.vat.inputtax.db.BCInputTaxDAO;
import com.ttl.common.util.CommonUtils;
import com.ttl.common.util.Page;

public class BCStkRefundBO {

	@SuppressWarnings("unchecked")
	public BCStkRefundForm findStkRefund(HttpServletRequest request) {
		BCStkRefundForm sf = new BCStkRefundForm();
		
		String docNo = (String)request.getParameter("docNo");
		
		List sfList = new BCStkRefundDAO().find("FROM BCStkRefund WHERE docNO = '"+docNo+"'");
		for (int i = 0; i < sfList.size(); i++) {
			BCStkRefund bean = (BCStkRefund)sfList.get(i);
			
			sf.setDocNo(bean.getDocNo());
			sf.setTaxNo(bean.getTaxNo());		
			sf.setDocDate(CommonUtils.convertDateToString(bean.getDocDate()));									
			sf.setDueDate(CommonUtils.convertDateToString(bean.getDueDate()));
			sf.setTaxType(bean.getTaxType());										
			sf.setApCode(bean.getApCode());
			sf.setDepartCode(bean.getDepartCode());
			sf.setCauseType(bean.getCauseType());
			sf.setCauseCode(bean.getCauseCode());
			sf.setProjectCode(bean.getProjectCode());									
			sf.setBillGroup(bean.getBillGroup());
			sf.setTaxRate(bean.getTaxRate());																
			sf.setSumOldAmount(bean.getSumOldAmount());
			sf.setSumOfItemAmount(bean.getSumOfItemAmount());	
			sf.setSumofBeforeTax(bean.getSumofBeforeTax());
			sf.setSumOfTaxAmount(bean.getSumOfTaxAmount());
			sf.setSumOfTotalTax(bean.getSumOfTotalTax());
			sf.setSumOfExceptTax(bean.getSumOfExceptTax());
			sf.setSumTrueAmount(bean.getSumTrueAmount());
			sf.setMyDescription(bean.getMyDescription());
			sf.setCurrencyCode(bean.getCurrencyCode());
			sf.setExchangeRate(bean.getExchangeRate());

			sf.setTaxDate(CommonUtils.convertDateToString(bean.getDocDate()));
			Iterator itsub = bean.getBcStkRefundSubs().iterator();
			while (itsub.hasNext()) {
				BCStkRefundSub sfSub = (BCStkRefundSub) itsub.next();
				
				sf.setItemCode(sfSub.getItemCode());
				sf.setItemName(sfSub.getItemName());
				sf.setDocNoInv(sfSub.getInvoiceNo());
				sf.setDocNoInv2(sfSub.getInvoiceNo());
				sf.setPrice(sfSub.getPrice());
				sf.setDiscQty(sfSub.getDiscQty());
				sf.setBillQty(sfSub.getBillQty());
				sf.setPrice(sfSub.getPrice());
				sf.setDiscountWord(sfSub.getDiscountWord());
				sf.setDiscountAmount(""+sfSub.getDiscountAmount());
				sf.setAmount(sfSub.getAmount());
				sf.setWhCode(sfSub.getWhCode());
				sf.setShelfCode(sfSub.getShelfCode());
				sf.setUnitCode(sfSub.getUnitCode());
				
			}
			
			Iterator itInvSf = bean.getBcInvStkRefunds().iterator();
			System.out.println("inv stk size = "+bean.getBcInvStkRefunds().size());
			while (itInvSf.hasNext()) {
				BCInvStkRefund invSf = (BCInvStkRefund)itInvSf.next();
				//System.out.println(invSf.getStkRefundNo() +"\t\t"+invSf.getOldAmount());
				//sf.setDocNoInv(invSf.getStkRefundNo());
				sf.setOldAmount(invSf.getOldAmount());
				
				
			}
			List apList = new BCStkRefundDAO().find("FROM BCAPBean WHERE code = '"+bean.getApCode()+"'");
			if(apList!=null && apList.size()>0) {
				BCAPBean ap = (BCAPBean)apList.get(0);
				request.setAttribute("apName", ap.getName1());
			}
//			private	String	taxAmount;			
		}
		
		
		
		return sf;
	}		
	
	@SuppressWarnings("unchecked")
	public Object findInv(ActionForm form, HttpServletRequest request) {

		InvFindForm invForm =(InvFindForm)form;
		String docNo = "";
		for(int i=0; i<invForm.getDocNoArray().length; i++) {
			docNo = docNo +"'"+ invForm.getDocNoArray()[i].trim() + "',";
		}
		if(docNo.length()>0) {
			docNo = docNo.substring(0, docNo.length()-1);
		}
		
		String hql = "FROM BCAPInvoiceBean " +
		 "WHERE  " +
		 " docNo in ( "+docNo+" )  ";		
		
		System.out.println(hql);
		
		BCAPInvoiceDAO dao = new BCAPInvoiceDAO();
		ArrayList results = (ArrayList)dao.find(hql);
		
		BCStkRefundForm sf = new BCStkRefundForm();
		if(results!=null && results.size()>0) {
			BCAPInvoiceBean i = (BCAPInvoiceBean)results.get(0);
						
			sf.setApCode(i.getApCode());
			sf.setDepartCode(i.getDepartCode());
			
			sf.setDocNoInv(i.getDocNo());
			sf.setOldAmount(i.getTotalAmount());
			
			Iterator it = i.getBcAPInvoiceSubs().iterator();
			while (it.hasNext()) {
				BCAPInvoiceSubBean isub = (BCAPInvoiceSubBean) it.next();
				sf.setItemCode(isub.getItemCode());
				sf.setItemName(isub.getItemName());
				sf.setDocNoInv2(i.getDocNo());
				sf.setPrice(isub.getPrice());
				sf.setBillQty(isub.getQty());
				sf.setWhCode(isub.getWhCode());
				sf.setShelfCode(isub.getShelfCode());
				sf.setUnitCode(isub.getUnitCode());
			}
			
			ArrayList apList = (ArrayList)(new BCAPDAO().find(i.getApCode()));
			if(apList!=null && apList.size()>0) {
				BCAPBean ap = (BCAPBean)apList.get(0);
				request.setAttribute("apCode", ap.getCode());
				request.setAttribute("apName", ap.getName1());
				
			}
		}
		
		return sf;//alSort;//alSort;//al;
	}

	@SuppressWarnings("unchecked")
	public ArrayList findItem(ArrayList results) {
		
		ArrayList results_item = new ArrayList();
		if(results!=null && results.size()>0) {
			int lineCount = 0;
			for (int i = 0; i < results.size(); i++) {
				BCAPInvoiceBean inv = (BCAPInvoiceBean)results.get(i);
				Iterator it = inv.getBcAPInvoiceSubs().iterator();
				while (it.hasNext()) {
					BCAPInvoiceSubBean isub = (BCAPInvoiceSubBean) it.next();
					
					BCStkRefundSub stkSub = new BCStkRefundSub();
					stkSub.setItemCode(isub.getItemCode());
					stkSub.setItemName(isub.getItemName());
					stkSub.setInvoiceNo(inv.getDocNo());
					stkSub.setWhCode(isub.getWhCode());
					stkSub.setShelfCode(isub.getShelfCode());
					stkSub.setUnitCode(isub.getUnitCode());
					
					stkSub.setDepartCode(isub.getDepartCode());
					stkSub.setProjectCode(isub.getProjectCode());
					stkSub.setBillQty(isub.getQty());
					stkSub.setLineNumber(lineCount++);
										
					stkSub.setDiscQty(0d);
					stkSub.setPrice(isub.getPrice());
					stkSub.setDiscountAmount(0d);
					stkSub.setAmount(0d);
					
					stkSub.setBillQty(isub.getQty());
					results_item.add(stkSub);
					
				}
			}
		}
		
		return results_item;
	}

	@SuppressWarnings("unchecked")
	public boolean add(ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		
		BCStkRefund  cn = (BCStkRefund)BCStkRefundBO.getObject(form);
		
		String user 	 = (String)request.getSession().getAttribute("userName");
		cn.setCreatorCode(user);
		cn.setCreateDateTime(new Date());
		
		new BCStkRefundDAO().add(cn);
		// ถ้ามีเลขที่ใบกำกับภาษี (taxNo) ให้เพิ่มใน BCInputTax 		
		if(cn.getTaxNo()!=null && !cn.getTaxNo().equals("")) {
			BCInputTaxBean tax = (BCInputTaxBean)BCInputTaxBO.getObjectCN(form);
			tax.setCreatorCode(user);
			new BCInputTaxDAO().add(tax);
		}
		
		BCAPDAO apDao = new BCAPDAO();
		apDao.updateDebtAmount(cn.getApCode(), cn.getSumOfTotalTax(), "CN");		
		System.out.println("update :DebtAmount"); 		
		
		ITTL_P2 p2 = (ITTL_P2)getCNForP2(cn);
		
		
		ArrayList unitList = (ArrayList)request.getSession().getAttribute("unitCodeList");
		for (int j = 0; j < unitList.size(); j++) {
			BCItemUnitBean uBean = (BCItemUnitBean)unitList.get(j);
			if(p2.getUnitName().equals(uBean.getCode())) {
				p2.setUnitName(uBean.getName());
				break;
			}						
		}		
		new BCStkRefundDAO().add(p2);
		
		// ใส่ข้อมูล itemCode รายการนั้นใน table: processStock 
		ProcessStockDAO p = new ProcessStockDAO();
		String[] item_of_service = {"A-01", "A-02", "C-3",  "D-03", "D-04", "D-4",  "E-04", "E-05", "E-4",  "E-5",  "E-S-E",
									"F-04", "F-05", "F-06", "F-4",  "F-5",  "F-6",  "G-06", "G-08", "G-10", "G-11", "G-12", 
									"G-13", "G-14", "G-24", "GE",   "H-07", "H-08", "H-15", "HO",   "I-10", "I-16", "IM",
									"INT",  "J-11", "J-17", "K-14", "K-15", "K-16", "K-17", "K-18", "L-18", "L-19", "M-19",
									"M-21", "N-20", "N-22", "O-21", "P-22", "P-23", "Q-23", "R-24", "R-25", "S-25", "SE", "TREEX", "TRECO", 
									"SER-006","SES","ST",   "T-26", "U-27", "V-28", "Z-01", "Z-02", "Z-03", "Z-04", "Z-05", "Z-06"};
		
		Iterator it = cn.getBcStkRefundSubs().iterator();
		
		while(it.hasNext()) {
			BCStkRefundSub sub = (BCStkRefundSub)it.next();
								
			boolean isItemService = false;
			for (int i = 0; i < item_of_service.length; i++) {
				if(item_of_service[i].contains(sub.getItemCode())) {
					isItemService = true;
				}				
			}
			if(isItemService==false) {
	        	ProcessStockBean bean = new ProcessStockBean();
	        	bean.setItemCode(sub.getItemCode());
	        	bean.setDocDate(sub.getDocDate());
	        	bean.setProcessFlag(0);
	        	bean.setFlowStatus(1);
	        	bean.setProcessType(6);//	สำหรับลดหนี้
	        	bean.setProcessCase(1);//  บันทึกเอกสารให้ =1, แก้ไขเอกสารให้=2,ลบเอกสารให้=3
	        		        	
	        	p.add(bean);
	        	
	    		System.out.println(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :ProcessStockDAO #mode :add "+
	  				  "#item:"+sub.getItemCode());
// 				BCWinService จะ update: lastBuyPrice ให้กับ item ที่ซื้อเข้ามา แบบ auto อยู่แล้ว	
//	    		new BCItemDAO().updateLastBuyPrice(sub.getItemCode(),sub.getPrice());
	    		
			}
		}		
		request.setAttribute("docNoPrint", p2.getDocNo());
		//request.setAttribute("docNoFind", inv.getDocNo());
				
//		String user 	 = (String)request.getSession().getAttribute("userName");
//		System.out.println(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :BCAPInvoiceDAO #mode :add");		
//		
//		BCAPInvoiceDAO dao = new BCAPInvoiceDAO();
//		String hql = "FROM BCAPInvoiceBean WHERE docNo = '"+inv.getDocNo()+"' ";
//		List al = dao.find(hql);
//		if(al!=null && al.size()>0) {
//			String maxDocNo = CommonUtils.getMaxBCAPInvoiceDocNo(inv.getDocNo());
//			inv.setDocNo(maxDocNo);			
//		}	
//		
//		if(inv.getDocNo().substring(0, 3).equalsIgnoreCase("BCS")) {
//			//บันทึกเงินสดย่อย
//			BCPayMoneyBean pay = (BCPayMoneyBean)BCPayMoneyBO.getObject(form);			
//			BCPayMoneyDAO dao4 = new BCPayMoneyDAO();
//			dao4.add(pay);
//			
//			// ถ้ามูลค่าสุทธิ < ยอดรวมสินค้า   ->ถือเป็นหัก ณ ที่จ่าย			
//			if(inv.getNetDebtAmount().doubleValue()<inv.getTotalAmount().doubleValue()) {
//				BCAPWTaxListBean wTax = (BCAPWTaxListBean)BCAPWTaxListBO.getObject(form);
//				BCAPWTaxListDAO dao6 = new BCAPWTaxListDAO();
//				dao6.add(wTax);
//				
//				inv.setSumOfWTax(wTax.getwTaxAmount());
//			}			
//		}else if(inv.getDocNo().substring(0, 3).equalsIgnoreCase("CRS") ||
//					inv.getDocNo().substring(0, 3).equalsIgnoreCase("CMD")) {				
//				BCAPDAO apDao = new BCAPDAO();
//				apDao.updateDebtAmount(inv);
//				System.out.println("update :DebtAmount"); 
//		}
//		
//		// ถ้ามีเลขที่ใบกำกับภาษี (taxNo) ให้เพิ่มใน BCInputTax 		
//		if(inv.getTaxNo()!=null && !inv.getTaxNo().equals("")) {
//			BCInputTaxBean tax = (BCInputTaxBean)BCInputTaxBO.getObject(form);
//			BCInputTaxDAO dao5 = new BCInputTaxDAO();
//			dao5.add(tax);
//		}		
//		dao.add(inv);
//		
//		dao.addITTL_P2(inv);
//		
//		// ใส่ข้อมูล itemCode รายการนั้นใน table: processStock 
//		ProcessStockDAO p = new ProcessStockDAO();
//		String[] item_of_service = {"A-01", "A-02", "C-3",  "D-03", "D-04", "D-4",  "E-04", "E-05", "E-4",  "E-5",  "E-S-E",
//									"F-04", "F-05", "F-06", "F-4",  "F-5",  "F-6",  "G-06", "G-08", "G-10", "G-11", "G-12", 
//									"G-13", "G-14", "G-24", "GE",   "H-07", "H-08", "H-15", "HO",   "I-10", "I-16", "IM",
//									"INT",  "J-11", "J-17", "K-14", "K-15", "K-16", "K-17", "K-18", "L-18", "L-19", "M-19",
//									"M-21", "N-20", "N-22", "O-21", "P-22", "P-23", "Q-23", "R-24", "R-25", "S-25", "SE", "TREEX", "TRECO", 
//									"SER-006","SES","ST",   "T-26", "U-27", "V-28", "Z-01", "Z-02", "Z-03", "Z-04", "Z-05", "Z-06"};
//		
//		Iterator it = inv.getBcAPInvoiceSubs().iterator();
//		
//		while(it.hasNext()) {
//			BCAPInvoiceSubBean sub = (BCAPInvoiceSubBean)it.next();
//									
//			BCStkRequestDAO dao2 = new BCStkRequestDAO();
//			//dao2.updateStatus(sub.getPoRefNo());
//			
//			//update ว่าใบ พ.1 ขอซื้อนั้น ใช้บันทึกซื้อแล้ว (แม้ไม่ได้ซึ้อทุก item )
//			dao2.updateStatus(sub.getStkReqNo(),"2"); //0=รอเบิก, 1=รอซื้อสร้าง po แล้ว, 2=ซื้อแล้ว, 3=จ่ายแล้ว, 4=ยืนยันรับของ
//			//update item ที่ซื้อเข้ามาตาม rowOrder
//			dao2.updateStatusAfterCreateInvoice(form,"2");
//			
////			BCReqConfirmDAO dao3 = new BCReqConfirmDAO();
////			//dao3.updateStatus(sub.getPoRefNo());
////			dao3.updateStatus(sub.getStkReqNo(),"2");
//			
//			BCPurchaseOrderDAO dao4 = new BCPurchaseOrderDAO();
//			dao4.updateStatusAfterSaveInvoice(sub.getPoRefNo());// หลังจาก save invoice จะต้อง update : poStatus=2, billStatus=1
//								
//			boolean isItemService = false;
//			for (int i = 0; i < item_of_service.length; i++) {
//				if(item_of_service[i].equalsIgnoreCase(sub.getItemCode())) {
//					isItemService = true;
//				}				
//			}
//			if(isItemService==false) {
//	        	ProcessStockBean bean = new ProcessStockBean();
//	        	bean.setItemCode(sub.getItemCode());
//	        	bean.setDocDate(sub.getDocDate());
//	        	bean.setProcessFlag(0);
//	        	bean.setFlowStatus(1);
//	        	bean.setProcessType(5);
//	        	bean.setProcessCase(1);// สำหรับ BCStkIssue บันทึกเอกสารให้ =1, ลบเอกสารให้=3
//	        		        	
//	        	p.add(bean);
//	        	
//	    		System.out.println(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :ProcessStockDAO #mode :add "+
//	  				  "#item:"+sub.getItemCode());
//// 				BCWinService จะ update: lastBuyPrice ให้กับ item ที่ซื้อเข้ามา แบบ auto อยู่แล้ว	
////	    		new BCItemDAO().updateLastBuyPrice(sub.getItemCode(),sub.getPrice());
//	    		
//			}
//			//###########
//		}
//// Start: เพื่อ update purchaseOrder
//		BCAPInvoice2Form invForm = (BCAPInvoice2Form)form;
//// end: เพื่อ update purchaseOrder		
		return true;
	}

	@SuppressWarnings("unchecked")
	private ITTL_P2 getCNForP2(BCStkRefund stkRef) {
		ITTL_P2 p2 = new ITTL_P2();
		
		
		//p2.setPoRefNo(stkRef.getDocNo());
		p2.setDocNo(stkRef.getDocNo());
		p2.setTaxNo(stkRef.getTaxNo());
		
		p2.setSumOfItemAmountOfPO(stkRef.getSumOfItemAmount());
		p2.setTaxAmountOfPO(stkRef.getSumOfTaxAmount());
		p2.setTotalAmountOfPO(stkRef.getSumOfTotalTax());
		
		p2.setSumOfItemAmountOfInvoice(stkRef.getSumOfItemAmount());
		p2.setTaxAmountOfInvoice(stkRef.getSumOfTaxAmount());
		p2.setTotalAmountOfInvoice(stkRef.getSumOfTotalTax());
		p2.setApCode(stkRef.getApCode());
		p2.setDocDate(stkRef.getDocDate());
		p2.setPoDate(stkRef.getDocDate());
		Iterator it = stkRef.getBcStkRefundSubs().iterator();
		while (it.hasNext()) {
			BCStkRefundSub sub = (BCStkRefundSub) it.next();
			p2.setItemCode(sub.getItemCode());
			p2.setItemName(sub.getItemName());
			p2.setQty(sub.getDiscQty());
			p2.setPrice(sub.getPrice());
			p2.setDiscountWordLineItem(sub.getDiscountWord());
			p2.setDiscountAmountLineItem(sub.getDiscountAmount());
			p2.setAmount(sub.getAmount());
			
			p2.setUnitName(sub.getUnitCode());
			p2.setIttl_purchaseCode(sub.getInvoiceNo());
		}
		
		//private	String	docnO
		
		//private	String	discountWordLineItem;		//		discountWordLineItem 	varchar(50) 		NULL,
		//private	Double   discountAmountLineItem;	//		discountAmountLineItem	money 				NULL,
		//private	Double   amount;  					//		amount 					money 				NULL,
		//private	Double   sumOfItemAmountOfPO;		//		sumOfItemAmountOfPO 	money 				NULL,
		//private	Double   taxAmountOfPO;  			//		taxAmountOfPO 			money 				NULL,
		//private	Double   totalAmountOfPO; 			//		totalAmountOfPO 		money 				NULL,
		//private	Double   sumOfItemAmountOfInvoice;	//		sumOfItemAmountOfInvoice money 				NULL,
		//private	Double   taxAmountOfInvoice; 		//		taxAmountOfInvoice 		money 				NULL,
		//private	Double   totalAmountOfInvoice;		//		totalAmountOfInvoice 	money 				NULL,
		//private	String	billGroup;   				//		billGroup 				varchar(50) 		NULL,
		//private	Date	docDate;   					//		docDate 				date 				NULL,
		//private	String	apCode;   					//		apCode 					varchar(50) 		NULL,
		//private	String	apName;   					//		apName 					varchar(250) 		NULL,
		//private	Date	poDate;						//		poDate 					date 				NULL,
		//private	String	ittl_purchaseCode; 			//		ittl_purchaseCode 		varchar(50) 		NULL,
		//private	String	tempMyDesc3;  				//		tempMyDesc3 			varchar(50) 		NULL,
		//private	String	tempMyDesc4;				//		tempMyDesc4 			varchar(50) 		NULL,
		//private	String	tempMyDesc5;				//		tempMyDesc5 			varchar(50) 		NULL,
		//private	String	tempMyDesc6;				//		tempMyDesc6 			varchar(50) 		NULL,
		//private	String	ittl_payment;				//		ittl_payment 			varchar(50) 		NULL,
		//private	String	stkReqNo;					//		stkReqNo 				varchar(50) 		NULL,
		//private	String	unitName;					//		unitName 				varchar(50) 		NULL
		//private	String	taxNo;
		
		return p2;
	}

	@SuppressWarnings("unchecked")
	private static BCStkRefund getObject(ActionForm form) {
		
		BCStkRefundForm sForm = (BCStkRefundForm)form;
		
		BCStkRefund s = new BCStkRefund();
		s.setDocNo(sForm.getDocNo());
		s.setTaxNo(sForm.getTaxNo());
		s.setDocDate(CommonUtils.convertStringToDate(sForm.getDocDate()));
		s.setDueDate(CommonUtils.convertStringToDate(sForm.getDueDate()));
		s.setTaxType(sForm.getTaxType());
		s.setApCode(sForm.getApCode());
		s.setDepartCode(sForm.getDepartCode());
		s.setTaxRate(7d);
		s.setIsConfirm(0);
		s.setSumOfItemAmount(sForm.getSumOfItemAmount());
		s.setSumOldAmount(sForm.getOldAmount());
		s.setSumTrueAmount(sForm.getSumTrueAmount());
		s.setSumofBeforeTax(sForm.getSumOfItemAmount());
		s.setSumOfTaxAmount(sForm.getSumOfTotalTax()-sForm.getSumOfItemAmount());
		s.setSumOfTotalTax(sForm.getSumOfTotalTax());
		
		s.setSumOfExceptTax(0d);
		s.setSumOfZeroTax(0d);
		s.setNetDebtAmount(sForm.getSumOfTotalTax());
		s.setSumExchangeProfit(0d);
		s.setBillBalance(sForm.getSumOfTotalTax());
		s.setCurrencyCode("BAHT");
		s.setExchangeRate(1d);
		s.setGlFormat("P05");
		s.setGlStartPosting(1);
		s.setIsPostGL(0);
		s.setIsCancel(0);
		s.setIsProcessOK(0);
		s.setIsCompleteSave(1);
		s.setGlTransData(0);
		
		s.setReturnMoney(0);
		s.setReturnStatus(0);
		s.setStatementState(0);
		s.setBillType(0);
		s.setCauseType(sForm.getCauseType());
		s.setCauseCode(sForm.getCauseCode());
		s.setProjectCode(sForm.getProjectCode());
		s.setBillGroup(sForm.getBillGroup());
		
		s.setPayBillAmount(sForm.getSumOfTotalTax());
		s.setPrepayAmount(sForm.getSumOfTotalTax());
		s.setMyDescription("data from iTTL");
		
		
		
		HashSet hashSetInv = new HashSet();			
		
//		for(int i=0; i<sForm.getInvoiceNo2().length; i++ ) {
			BCInvStkRefund invStk = new BCInvStkRefund();
			invStk.setDocDate(CommonUtils.convertStringToDate(sForm.getDocDate()));
			invStk.setApCode(sForm.getApCode());
			invStk.setStkRefundNo(sForm.getDocNo());
			invStk.setReturnMoney(0);
			invStk.setReturnStatus(0);
			invStk.setInvoiceNo(sForm.getDocNoInv());
			invStk.setInvExchangeRate(1d);
			invStk.setNewExchangeRate(1d);
			invStk.setOldAmount(sForm.getOldAmount());
			invStk.setSumOfItemAmount(sForm.getSumOfItemAmount());
			invStk.setDiscountAmount(0d);
			invStk.setDiffAmount(sForm.getSumOfTotalTax());
			invStk.setZeroTaxAmount(0d);
			invStk.setExceptTaxAmount(0d);
			invStk.setTrueAmount(sForm.getSumTrueAmount());
			invStk.setHomeAmount1(sForm.getSumOfTotalTax());
			invStk.setHomeAmount2(sForm.getSumOfTotalTax());
			
			invStk.setExchangeProfit(sForm.getSumOfTotalTax());
			invStk.setIsCancel(0);
			invStk.setBillType(0);
			
			
			invStk.setBcStkRefund(s);
			hashSetInv.add(invStk);
//		}
		s.setBcInvStkRefunds(hashSetInv);	
		
		HashSet hashSet = new HashSet();			
		
//		for(int i=0; i<sForm.getItemCode().length; i++ ) {
											
			BCStkRefundSub sub = new BCStkRefundSub();
			sub.setMyType(7);
			sub.setTaxNo(s.getTaxNo());
			sub.setTaxType(s.getTaxType());
			sub.setItemCode(sForm.getItemCode());
			sub.setDocDate(s.getDocDate());
			sub.setApCode(s.getApCode());
			sub.setDepartCode(s.getDepartCode());
			sub.setWhCode("10");
			sub.setShelfCode("10");
			sub.setDiscQty(sForm.getDiscQty());
			sub.setTempQty(sForm.getDiscQty());
			sub.setBillQty(sForm.getBillQty());
			sub.setPrice(sForm.getPrice());
			
			if(CommonUtils.isNumberPercent(sForm.getDiscountAmount())) {
				sub.setDiscountWord(sForm.getDiscountAmount());
				double percent1 = Double.valueOf( sForm.getDiscountAmount().substring(0, sForm.getDiscountAmount().length()-1) );
				
				DecimalFormat f = new DecimalFormat("#.00");
				double subDiscountAmount = Double.valueOf( f.format(sub.getDiscQty()* sub.getPrice()*percent1/100));
				sub.setDiscountAmount(subDiscountAmount);
			}else {
				sub.setDiscountWord(sForm.getDiscountAmount()  );
				sub.setDiscountAmount(Double.valueOf(sForm.getDiscountAmount()  ));
			}
			sub.setAmount(sForm.getAmount());
			sub.setNetAmount(sForm.getAmount());
			sub.setHomeAmount(sForm.getAmount());
			sub.setUnitCode(sForm.getUnitCode());
			sub.setInvoiceNo(sForm.getDocNoInv2());
			sub.setProjectCode(s.getProjectCode());
			sub.setCurrencyCode("BAHT");
			sub.setExchangeRate(1d);
			sub.setTransState(0);
			sub.setIsCancel(0);
			sub.setStockProcess(0);
			sub.setLineNumber(1);
			
			sub.setSumOfCost(sub.getAmount());
			sub.setItemName(sForm.getItemName());
			sub.setCauseType(s.getCauseType());
			sub.setTaxRate(s.getTaxRate());
			sub.setIsProcess(1);
			sub.setItemType(1);
			sub.setExceptTax(0);
			sub.setBcStkRefund(s);			
			hashSet.add(sub);
//		}
			
		s.setBcStkRefundSubs(hashSet);
		return s;
	}

	
	public void showFind(HttpServletRequest request) throws UnsupportedEncodingException {
//		String userName = (String)request.getSession().getAttribute("userName");			
		String monthFind = (String)request.getParameter("monthFind");
		String yearFind = (String)request.getParameter("yearFind");

//		String preDocNo  = (String)request.getSession().getAttribute("preDocNo")+"";
//		int userLevel =  (Integer)request.getSession().getAttribute("userLevel");		

		String	itemFind = "";
		if(request.getParameter("itemFind")!=null) {
			itemFind = ((String)request.getParameter("itemFind"));
			itemFind = new String(itemFind.getBytes("ISO8859_1"),"UTF-8");
			request.setAttribute("itemFind", itemFind.trim());
		}		
		
		if(monthFind==null) {			
			monthFind = CommonUtils.getCurrentDateFormat("MM");										
		}
		
		if(yearFind==null) {
			yearFind = CommonUtils.getCurrentDateFormat("yyyyy");
			
			if (Integer.parseInt(yearFind)<2500) {								
				yearFind = (""+(Integer.parseInt(yearFind)+543)).substring(2);			
			}else {
				yearFind = yearFind.substring(2);
			}			
		}
				
		request.getSession().setAttribute("monthFind", monthFind);
		request.getSession().setAttribute("yearFind", yearFind);
		
		String hql = "";
		if(itemFind==null||itemFind.trim().equals("")) {
			hql = "FROM BCStkRefund   " +
					 " WHERE (docNo like 'cn%' ) " +
					 " ORDER BY docNo desc";			
		}else {
			hql = "FROM BCStkRefund  " +
			 		 " WHERE (docNo like 'cn%'  ) " +
					 " and (docNo  like '%"+itemFind.trim()+"%' or "+					 
					 "      taxNo like '%"+itemFind.trim()+"%') "+	
					 " ORDER BY docNo desc";
		}
		System.out.println(hql);
		Page.setPage(request, hql);	
	}

	public boolean delete(ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
				
		BCStkRefundForm sf = (BCStkRefundForm)form;		

		String user 	 = (String)request.getSession().getAttribute("userName");
		System.out.println(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :BCStkRefundDAO #mode :delete");		
		
		request.setAttribute("itemFind", sf.getDocNo());
		
		return new BCStkRefundDAO().deleteCN(sf.getDocNo());
	}


}
